<template>
  <div>
    <h1>优惠券列表</h1>
    <!-- 条件搜索 -->
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="优惠券名称">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入优惠券名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadCouponList">查询</el-button>
          <el-button type="primary" @click="onAddCoupon">添加优惠券</el-button>
          <el-button type="info" @click="onClaimRecords">领取记录</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格数据 -->
    <div style="margin-top: 10px">
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="couponId" label="序号" width="60" />
        <el-table-column prop="couponName" label="优惠券名称" width="100" />
        <el-table-column prop="couponType" label="优惠券类型" width="100" />
        <el-table-column prop="useType" label="适用类型" width="80" />
        <el-table-column prop="couponValue" label="面值" width="80" />
        <el-table-column prop="getType" label="领取方式" width="80" />
        <el-table-column prop="getTime" label="领取日期" width="300">
          <template #default="scope">
            <span v-if="scope.row.getTime == 1"
              >{{ scope.row.beginTime }}至{{ scope.row.endTime }}</span
            >
            <span v-if="scope.row.getTime == 2"
              >不限时</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="useDay" label="使用时间" width="300">
          <template #default="scope">
            <span v-if="scope.row.useDay == 1">{{ scope.row.dayNum }}天</span>
            <span v-if="scope.row.useDay == 2"
              >{{ scope.row.beginTime }}至{{ scope.row.endTime }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="limitNum" label="发布数量" width="80">
          <template #default="scope">
            <span v-if="scope.row.limitNum == null || scope.row.limitNum == ''"
              >不限量</span
            >
            <span v-if="scope.row.limitNum != null">{{
              scope.row.limitNum
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="couponStatus" label="有效状态" width="80" />
        <el-table-column label="操作" >
            <template #default="scope">
                <el-button type="primary" size="small" @click="onClaim(scope.row)">领取</el-button>
            </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div style="margin-top: 10px">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加优惠券---对话框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加优惠券" width="600">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item label="优惠券类型" :label-width="formLabelWidth">
            <el-radio-group v-model="form.couponType">
              <el-radio
                v-for="item in couponTypeList"
                :value="item.dictValue"
                :key="item.dictId"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="优惠券名称"
            :label-width="formLabelWidth"
            prop="couponName"
          >
            <el-input v-model="form.couponName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="最低使用金额" :label-width="formLabelWidth">
            <el-input v-model="form.minAmount" autocomplete="off" />
          </el-form-item>
          <el-form-item label="优惠券面值" :label-width="formLabelWidth">
            <el-input v-model="form.couponValue" autocomplete="off" />
          </el-form-item>
          <el-form-item label="领取方式" :label-width="formLabelWidth">
            <el-radio-group v-model="form.getType">
              <el-radio
                v-for="item in getTypeList"
                :value="item.dictValue"
                :key="item.dictId"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="适用类型" :label-width="formLabelWidth">
            <el-radio-group v-model="form.useType">
              <el-radio
                v-for="item in useTypeList"
                :value="item.dictValue"
                :key="item.dictId"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="使用门槛" :label-width="formLabelWidth">
            <el-radio-group v-model="form.useDoor">
              <el-radio
                v-for="item in useDoorList"
                :value="item.dictValue"
                :key="item.dictId"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="使用时间" :label-width="formLabelWidth">
            <el-radio-group v-model="form.useDay">
              <el-radio
                v-for="item in useDayList"
                :value="item.dictValue"
                :key="item.dictId"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
            <div>
              <el-input
                v-model="form.dayNum"
                v-if="form.useDay == 1"
                placeholder="请输入使用天数"
              />
              <el-date-picker
                v-model="form.useTimes"
                type="datetimerange"
                start-placeholder="开始时间"
                end-placeholder="截止时间"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="YYYY/MM/DD ddd"
                time-format="A hh:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-if="form.useDay == 2"
              />
            </div>
          </el-form-item>
          <el-form-item label="领取时间" :label-width="formLabelWidth">
            <el-radio-group v-model="form.getTime">
              <el-radio
                v-for="item in getTimeList"
                :value="item.dictValue"
                :key="item.dictId"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
            <div>
                <el-date-picker
                v-model="form.useTimes"
                type="datetimerange"
                start-placeholder="开始时间"
                end-placeholder="截止时间"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="YYYY/MM/DD ddd"
                time-format="A hh:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-if="form.getTime == 1"
              />
            </div>
          </el-form-item>
          <el-form-item label="是否限量" :label-width="formLabelWidth">
            <el-radio-group v-model="form.limitFlag">
              <el-radio
                v-for="item in limitFlagList"
                :value="item.dictValue"
                :key="item.dictId"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
            <div>
              <el-input
                v-model="form.limitNum"
                v-if="form.limitFlag == 1"
                placeholder="请输入发布数量"
              />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              完成
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { getCouponList, getDietList, addCoupon,claimCoupon } from "../api/api";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();

const tableData = ref([]);
const total = ref(0);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: "",
});

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const ruleFormRef = ref<FormInstance>();
const form = ref({
  beginTime: "",
  couponName: "",
  couponStatus: 0,
  couponType: null,
  minAmount: 0.0,
  couponValue: 0.0,
  dayNum: null,
  endTime: "",
  getBeginTime: "",
  getEndTime: "",
  getTime: null,
  getType: null,
  limitFlag: null,
  limitNum: null,
  useDay: null,
  useDoor: null,
  useType: null,
  useTimes: null,
  getTimes: null,
});

//领取记录
const onClaimRecords = () => {
  console.log("onClaimRecords");
  router.push("/home/claim");
}

//领取优惠券
const onClaim = (row:any) => {
    console.log("onClaim",row);
    claimCoupon(row.couponId).then(res=>{
      if(res.data.code == 200){
        ElMessage.success("领取成功");
        loadCouponList();
      }else{
        ElMessage.error(res.data.msg);
      }
    })
}

//显示添加优惠券对话框
const onAddCoupon = () => {
  console.log("onAddCoupon");
  form.value = {
    beginTime: "",
    couponName: "",
    couponStatus: 0,
    couponType: null,
    minAmount: 0.0,
    couponValue: 0.0,
    dayNum: null,
    endTime: "",
    getBeginTime: "",
    getEndTime: "",
    getTime: null,
    getType: null,
    limitFlag: null,
    limitNum: null,
    useDay: null,
    useDoor: null,
    useType: null,
    useTimes: null,
    getTimes: null,
  };
  dialogFormVisible.value = true;
};

//添加校验
const rules = reactive<any>({
  couponName: [
    { required: true, message: "请输入优惠券名称", trigger: "blur" },
  ],
});
//确认添加优惠券
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      onSumbitAddCoupon();
    } else {
      console.log("error submit!", fields);
    }
  });
};
const onSumbitAddCoupon = () => {
  console.log("onSumbitAddCoupon");
  addCoupon(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      loadCouponList();
      dialogFormVisible.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadCouponList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadCouponList();
};

//查询列表
const loadCouponList = () => {
  getCouponList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

const couponTypeList = ref([]);
const getTypeList = ref([]);
const useTypeList = ref([]);
const useDayList = ref([]);
const useDoorList = ref([]);
const getTimeList = ref([]);
const limitFlagList = ref([]);

onMounted(() => {
  loadCouponList();
  getDietList(9).then((res) => {
    if (res.data.code == 200) {
      couponTypeList.value = res.data.data;
    }
  });
  getDietList(10).then((res) => {
    if (res.data.code == 200) {
      getTypeList.value = res.data.data;
    }
  });
  getDietList(11).then((res) => {
    if (res.data.code == 200) {
      useTypeList.value = res.data.data;
    }
  });
  getDietList(12).then((res) => {
    if (res.data.code == 200) {
      useDoorList.value = res.data.data;
    }
  });
  getDietList(13).then((res) => {
    if (res.data.code == 200) {
      useDayList.value = res.data.data;
    }
  });
  getDietList(14).then((res) => {
    if (res.data.code == 200) {
      getTimeList.value = res.data.data;
    }
  });
  getDietList(15).then((res) => {
    if (res.data.code == 200) {
      limitFlagList.value = res.data.data;
    }
  });
});
</script>

<!-- 分页样式 -->
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
<!-- 条件搜索样式 -->
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
